package com.wpre.vampiremq.mqclient;

import com.wpre.vampiremq.common.*;
import com.wpre.vampiremq.mqserver.core.BasicProperties;
import com.wpre.vampiremq.mqserver.core.ExchangeType;

import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2025-01-19
 * Time: 20:43
 */
public class Channel {
    private String channelId;
    //当前是哪个连接
    private Connection connection;
    //存储 后续客户端收到的服务器的响应
    private ConcurrentHashMap<String, BasicReturns> basicReturnMap = new ConcurrentHashMap<>();
    //对应的回调,如果当前Channel订阅了某个队列,就需要在此处记录下对应的回调是啥,当该队列的消息返回来的时候,调用回调
    private Consumer consumer = null;

    //告知服务器,客户端创建了新的channel
    public boolean createChannel() throws IOException {

        BasicArguments arguments = new BasicArguments();
        arguments.setChannelId(channelId);
        arguments.setRid(generateRid());
        Request request = new Request();
        request.setType(0x1);
        byte[] payload = BinaryTool.toBytes(arguments);
        request.setLength(payload.length);
        request.setPayload(payload);

        //构造出请求之后,发送请求
        connection.writeRequest(request);

        //等待服务器的响应
        BasicReturns returns = waitResult(arguments.getRid());
        return returns.isOk();
    }
    //这个方法来进行 阻塞等待服务器的响应
    private BasicReturns waitResult(String rid) {
        BasicReturns basicReturns  = null;
        //循环读取
        while ((basicReturns = basicReturnMap.get(rid)) == null) {
            //从map中读取,如果为空,包裹还没回来,阻塞等待
            synchronized (this) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }

        }
        //读取成功后,从哈希表中删除
        basicReturnMap.remove(rid);
        return basicReturns;
    }
    private String generateRid() {
        return "Vampire-" + UUID.randomUUID().toString();
    }
    //关闭channel(给服务器发送一个type = 0x2的请求)
    public boolean close() throws IOException {
        BasicArguments arguments = new BasicArguments();
        arguments.setRid(generateRid());
        arguments.setChannelId(channelId);
        byte[] payload = BinaryTool.toBytes(arguments);

        Request request = new Request();
        request.setLength(payload.length);
        request.setPayload(payload);
        request.setType(0x2);

        //发送请求
        connection.writeRequest(request);
        BasicReturns returns = waitResult(arguments.getRid());
        return returns.isOk();

    }
    //创建交换机(给服务器发送一个type = 0x3的请求)
    public boolean exchangeDeclare(String exchangeName, ExchangeType exchangeType, boolean durable, boolean autoDelete, Map<String, Object> arguments) throws IOException {
        ExchangeDeclareArguments exchangeDeclareArguments = new ExchangeDeclareArguments();
        exchangeDeclareArguments.setExchangeName(exchangeName);
        exchangeDeclareArguments.setExchangeType(exchangeType);
        exchangeDeclareArguments.setArguments(arguments);
        exchangeDeclareArguments.setDurable(durable);
        exchangeDeclareArguments.setAutoDelete(autoDelete);
        exchangeDeclareArguments.setRid(generateRid());
        exchangeDeclareArguments.setChannelId(channelId);
        byte[] payload = BinaryTool.toBytes(exchangeDeclareArguments);

        Request request = new Request();
        request.setPayload(payload);
        request.setType(0x3);
        request.setLength(payload.length);
        connection.writeRequest(request);
        BasicReturns returns = waitResult(exchangeDeclareArguments.getRid());

        return returns.isOk();
    }
    //删除交换机
    public boolean exchangeDelete(String exchangeName) throws IOException {
        ExchangeDeleteArguments arguments = new ExchangeDeleteArguments();
        arguments.setExchangeName(exchangeName);
        arguments.setRid(generateRid());
        arguments.setChannelId(channelId);

        byte[] payload = BinaryTool.toBytes(arguments);

        Request request = new Request();
        request.setPayload(payload);
        request.setLength(payload.length);
        request.setType(0x4);

        connection.writeRequest(request);
        BasicReturns returns = waitResult(arguments.getRid());
        return returns.isOk();
    }
    // 创建队列
    public boolean queueDeclare(String queueName, boolean durable, boolean exclusive, boolean autoDelete,
                                Map<String, Object> arguments) throws IOException {
        QueueDeclareArguments queueDeclareArguments = new QueueDeclareArguments();
        queueDeclareArguments.setRid(generateRid());
        queueDeclareArguments.setChannelId(channelId);
        queueDeclareArguments.setQueueName(queueName);
        queueDeclareArguments.setDurable(durable);
        queueDeclareArguments.setExclusive(exclusive);
        queueDeclareArguments.setAutoDelete(autoDelete);
        queueDeclareArguments.setArguments(arguments);
        byte[] payload = BinaryTool.toBytes(queueDeclareArguments);

        Request request = new Request();
        request.setType(0x5);
        request.setLength(payload.length);
        request.setPayload(payload);

        connection.writeRequest(request);
        BasicReturns basicReturns = waitResult(queueDeclareArguments.getRid());
        return basicReturns.isOk();
    }
    // 删除队列
    public boolean queueDelete(String queueName) throws IOException {
        QueueDeleteArguments arguments = new QueueDeleteArguments();
        arguments.setRid(generateRid());
        arguments.setChannelId(channelId);
        arguments.setQueueName(queueName);
        byte[] payload = BinaryTool.toBytes(arguments);

        Request request = new Request();
        request.setType(0x6);
        request.setLength(payload.length);
        request.setPayload(payload);

        connection.writeRequest(request);
        BasicReturns basicReturns = waitResult(arguments.getRid());
        return basicReturns.isOk();
    }
    // 创建绑定
    public boolean queueBind(String queueName, String exchangeName, String bindingKey) throws IOException {
        QueueBindArguments arguments = new QueueBindArguments();
        arguments.setRid(generateRid());
        arguments.setChannelId(channelId);
        arguments.setQueueName(queueName);
        arguments.setExchangeName(exchangeName);
        arguments.setBindingKey(bindingKey);
        byte[] payload = BinaryTool.toBytes(arguments);

        Request request = new Request();
        request.setType(0x7);
        request.setLength(payload.length);
        request.setPayload(payload);

        connection.writeRequest(request);
        BasicReturns basicReturns = waitResult(arguments.getRid());
        return basicReturns.isOk();
    }
    // 解除绑定
    public boolean queueUnbind(String queueName, String exchangeName) throws IOException {
        QueueUnbindArguments arguments = new QueueUnbindArguments();
        arguments.setRid(generateRid());
        arguments.setChannelId(channelId);
        arguments.setQueueName(queueName);
        arguments.setExchangeName(exchangeName);
        byte[] payload = BinaryTool.toBytes(arguments);

        Request request = new Request();
        request.setType(0x8);
        request.setLength(payload.length);
        request.setPayload(payload);

        connection.writeRequest(request);
        BasicReturns basicReturns = waitResult(arguments.getRid());
        return basicReturns.isOk();
    }
    // 发送消息
    public boolean basicPublish(String exchangeName, String routingKey, BasicProperties basicProperties, byte[] body) throws IOException {
        BasicPublishArguments arguments = new BasicPublishArguments();
        arguments.setRid(generateRid());
        arguments.setChannelId(channelId);
        arguments.setExchangeName(exchangeName);
        arguments.setRoutingKey(routingKey);
        arguments.setBasicProperties(basicProperties);
        arguments.setBody(body);
        byte[] payload = BinaryTool.toBytes(arguments);

        Request request = new Request();
        request.setType(0x9);
        request.setLength(payload.length);
        request.setPayload(payload);

        connection.writeRequest(request);
        BasicReturns basicReturns = waitResult(arguments.getRid());
        return basicReturns.isOk();
    }
    // 订阅消息
    public boolean basicConsume(String queueName, boolean autoAck, Consumer consumer) throws MQException, IOException {
        // 先设置回调.
        if (this.consumer != null) {
            throw new MQException("该 channel 已经设置过消费消息的回调了, 不能重复设置!");
        }
        this.consumer = consumer;

        BasicConsumeArguments arguments = new BasicConsumeArguments();
        arguments.setRid(generateRid());
        arguments.setChannelId(channelId);
        arguments.setConsumerTag(channelId);  // 此处 consumerTag 也使用 channelId 来表示了.
        arguments.setQueueName(queueName);
        arguments.setAutoAck(autoAck);
        byte[] payload = BinaryTool.toBytes(arguments);

        Request request = new Request();
        request.setType(0xa);
        request.setLength(payload.length);
        request.setPayload(payload);

        connection.writeRequest(request);
        BasicReturns basicReturns = waitResult(arguments.getRid());
        return basicReturns.isOk();
    }
    // 确认消息
    public boolean basicAck(String queueName, String messageId) throws IOException {
        BasicAckArguments arguments = new BasicAckArguments();
        arguments.setRid(generateRid());
        arguments.setChannelId(channelId);
        arguments.setQueueName(queueName);
        arguments.setMessageId(messageId);
        byte[] payload = BinaryTool.toBytes(arguments);

        Request request = new Request();
        request.setType(0xb);
        request.setLength(payload.length);
        request.setPayload(payload);

        connection.writeRequest(request);
        BasicReturns basicReturns = waitResult(arguments.getRid());
        return basicReturns.isOk();
    }
    public void putReturns(BasicReturns returns) {
        basicReturnMap.put(returns.getRid(), returns);
        //唤醒等待的线程
        synchronized (this) {
            notifyAll();
        }
    }










    public Channel(String channelId, Connection connection) {
        this.channelId = channelId;
        this.connection = connection;
    }

    public String getChannelId() {
        return channelId;
    }

    public void setChannelId(String channelId) {
        this.channelId = channelId;
    }

    public Connection getConnection() {
        return connection;
    }

    public void setConnection(Connection connection) {
        this.connection = connection;
    }

    public ConcurrentHashMap<String, BasicReturns> getBasicReturnMap() {
        return basicReturnMap;
    }

    public void setBasicReturnMap(ConcurrentHashMap<String, BasicReturns> basicReturnMap) {
        this.basicReturnMap = basicReturnMap;
    }

    public Consumer getConsumer() {
        return consumer;
    }

    public void setConsumer(Consumer consumer) {
        this.consumer = consumer;
    }
}
